// 获取画布元素和绘图上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 定义网格大小和蛇的初始位置
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let snake = [
    { x: 10, y: 10 }
];
let food = {
    x: Math.floor(Math.random() * tileCount),
    y: Math.floor(Math.random() * tileCount)
};
let direction = 'right';
let score = 0;

// 游戏循环函数
function gameLoop() {
    clearCanvas();
    drawSnake();
    moveSnake();
    drawFood();
    checkCollision();
    
}

// 清除画布
function clearCanvas() {
    ctx.fillStyle = '#f0f0f0';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
}

// 绘制蛇
function drawSnake() {
    ctx.fillStyle = '#000';
    snake.forEach(segment => {
        ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
    });
}

// 移动蛇
function moveSnake() {
    const head = { ...snake[0] };
    switch (direction) {
        case 'up':
            head.y--;
            break;
        case 'down':
            head.y++;
            break;
        case 'left':
            head.x--;
            break;
        case 'right':
            head.x++;
            break;
    }
    snake.unshift(head);

    // 检查是否吃到食物
    if (head.x === food.x && head.y === food.y) {
        score++;
        generateFood();
    } else {
        snake.pop();
        updateSnakeLengthDisplay()
    }
}

// 绘制食物
function drawFood() {
    ctx.fillStyle = 'red';
    ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
        }

// 生成新的食物位置
function generateFood() {
    food = {
        x: Math.floor(Math.random() * tileCount),
        y: Math.floor(Math.random() * tileCount)
    };
}

// 更新蛇长度显示
function updateSnakeLengthDisplay() {
    const snakeLengthElement = document.getElementById('snakeLength');
    if (snakeLengthElement) {
        snakeLengthElement.textContent = `蛇的长度: ${snake.length}`;
    }
}

// 检查碰撞
function checkCollision() {
    const head = snake[0];

    // 处理边界穿越
    if (head.x < 0) {
        head.x = tileCount - 1;
    } else if (head.x >= tileCount) {
        head.x = 0;
    }
    if (head.y < 0) {
        head.y = tileCount - 1;
    } else if (head.y >= tileCount) {
        head.y = 0;
    }

    // 检查是否撞到自己
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            alert('游戏失败！');
            isGameRunning = false;
            resetGame();
        }
    }
}

// 重置游戏
function resetGame() {
    snake = [
        { x: 10, y: 10 }
    ];
    direction = 'right';
    score = 0;
}

// 监听键盘事件
document.addEventListener('keydown', function (event) {
    switch (event.key) {
        case 'ArrowUp':
            if (direction !== 'down') direction = 'up';
            break;
        case 'ArrowDown':
            if (direction !== 'up') direction = 'down';
            break;
        case 'ArrowLeft':
            if (direction !== 'right') direction = 'left';
            break;
        case 'ArrowRight':
            if (direction !== 'left') direction = 'right';
            break;
    }
});

// 定义不同困难度对应的速度
const difficultySpeeds = {
    easy: 200,
    medium: 100,
    hard: 50
};

// 获取 DOM 元素
const startGameButton = document.getElementById('startGame');
const difficultySelect = document.getElementById('difficulty');

// 游戏是否正在运行
let isGameRunning = false;

// 开始游戏函数
function startGame() {
    if (!isGameRunning) {
        isGameRunning = true;
        const difficulty = difficultySelect.value;
        const speed = difficultySpeeds[difficulty];
        gameLoop(speed);
    }
}

// 绑定按钮点击事件
startGameButton.addEventListener('click', startGame);

// 修改游戏循环函数以接受速度参数
function gameLoop(speed) {
    clearCanvas();
    drawSnake();
    moveSnake();
    drawFood();
    checkCollision();
    setTimeout(() => gameLoop(speed), speed);
}

